﻿using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class EventDefinitionRule : ILRule<EventDefinitionHandle>
    {
        [ILInfo]
        public EventAttributes Attributes { get; }

        [ILInfo(true)]
        public string Name { get; }

        [ILInfo(true)]
        public EntityHandle Type { get; }

        public EventAccessors Accessors { get; }

        [ILInfo(ILInfoParseMethod.AsEntityHandleCollection)]
        public CustomAttributeHandleCollection CustomAttributes { get; }

        public EventDefinitionRule(
            EventAttributes attributes,
            string name,
            EntityHandle type)
            : base()
        {
            Attributes = attributes;
            Name = name;
            Type = type;
        }

        public EventDefinitionRule(MetadataReader reader, EventDefinitionHandle eventDefinitionHandle)
            : base(reader)
        {
            EventDefinition eventDefinition = reader.GetEventDefinition(eventDefinitionHandle);
            Attributes = eventDefinition.Attributes;
            Name = reader.GetString(eventDefinition.Name);
            Type = eventDefinition.Type;
            Accessors = eventDefinition.GetAccessors();
            CustomAttributes = eventDefinition.GetCustomAttributes();
        }

        public override EventDefinitionHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            EventDefinitionHandle eventDefinition = builder.AddEvent(
                attributes: Attributes,
                name: Name == null ? default : builder.GetOrAddString(Name),
                type: Type);
            designer.EventDefinitionNumber.Increment();
            return eventDefinition;
        }
    }
}